//
//  AppDelegate.m
//  TQY
//
//  Created by 甘世清 on 2024/7/5.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<UNUserNotificationCenterDelegate>
@property (nonatomic ,strong) UIVisualEffectView * visualEffectView;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[Manager SQ_getViewController]];
    self.window  = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window setRootViewController:nav];
    self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
    [self.window makeKeyAndVisible];
    [self UIUserNotificationSettings:application];
    return YES;
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}
//应用被用户往上划手动杀死的。在应用被用户手动杀死时会AppDelegate调用下面的方法
-(void)applicationWillTerminate:(UIApplication *)application {
    if ([UserModel share].token) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = [[TQYFMDBManager SQ_getMessageCount] integerValue];
    } else {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
}

-(void)UIUserNotificationSettings:(UIApplication *)application{
    //消息推送注册
    UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert;
    [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) {

    }];
    [application registerForRemoteNotifications];
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    DTLog(@"我收到的推送是什么%@",userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //TODO:处理远程推送内容
      
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionList);
//    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    [UIApplication sharedApplication].applicationIconBadgeNumber += 1;
    DTLog(@"收到的推送1 :%@",userInfo);
   
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"注册推送失败：%@",error);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
   
    if (![deviceToken isKindOfClass:[NSData class]]) return;
    const unsigned *tokenBytes = [deviceToken bytes];
    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    if ([hexToken isNotEmpty] ) {
        [Manager SQ_SetObject:hexToken FormKey:@"hexToken"];
        
        if ([[UserModel share].token isNotEmpty]&& ![[UserModel share].deviceToken isNotEmpty]) {
            NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject: hexToken forKey:@"deviceToken"];
            [HttpTool post:@"user/config" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
                [UserModel share].deviceToken = hexToken;
                [UserModel updateLocalUserModel:[UserModel share]];
            } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
             
            }];
        }
    }
}

#pragma mark - 程序将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    DTLog(@"------程序将要进入前台");
    //通知消息页面
   
    if ([UserModel share].token) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = [[TQYFMDBManager SQ_getMessageCount] integerValue];
    } else {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
   
}
- (void)applicationDidBecomeActive:(UIApplication *)application{
    
   
    if (self.visualEffectView) {
        [self.visualEffectView removeFromSuperview];
    }
}


#pragma mark - 程序将要进入后台
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    if ([UserModel share].token) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = [[TQYFMDBManager SQ_getMessageCount] integerValue];
    } else {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    DTLog(@"------程序将要进入后台");
    [self.window addSubview:self.visualEffectView];
}
- (UIVisualEffectView *)visualEffectView{
    if (!_visualEffectView) {
        UIBlurEffect * blureffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _visualEffectView = [[UIVisualEffectView alloc]initWithEffect:blureffect];
        _visualEffectView.frame = [UIScreen mainScreen].bounds;
    }
    return _visualEffectView;
}

@end
